<template>
  <div class="app-container" ref="appcontainer">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="100px"
    >
      <!-- <el-form-item label="表码" prop="name"> -->
      <el-select
        v-model="queryParams.businessType22"
        placeholder="类型"
        style="width: 8%; margin-right: 10px"
        @change="handleDetectionTypeChange($event)"
      >
        <el-option
          v-for="item in detection_type_options"
          :key="item.dictValue"
          :label="item.dictLabel"
          :value="item.dictValue"
        ></el-option>
      </el-select>
      <el-select
        v-model="queryParams.params.projectStr"
        placeholder="试验项目"
        style="width: 8%; margin-right: 10px"
        multiple
      >
        <el-option
          v-for="item in project_options"
          :key="item.dictLabel"
          :label="item.dictLabel"
          :value="item.dictLabel"
        ></el-option>
      </el-select>

      <el-form-item label="工程名称">
        <el-input
          v-model="queryParams.engineeringName"
          placeholder="工程名称"
          clearable
          size="small"
          style=" margin-right: 10px"
        />
      </el-form-item>

      <el-form-item label="报告编号">
        <el-input
          v-model="queryParams.reportNumber"
          placeholder="报告编号"
          clearable
          size="small"
          style=" margin-right: 10px"
        />
      </el-form-item>
      

      <el-form-item label="报告日期">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <!-- </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <!-- <el-button type="primary" size="mini" @click="handleAdd"
          >新增</el-button
        >
        <el-button type="primary" size="mini" @click="resetExport"
          >导出</el-button
        > -->
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-show="roleId != 6">
        <el-button type="primary" plain icon="" size="mini" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="" size="mini" @click="handleImport">导入
        </el-button>
      </el-col> -->

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="resetExport"
          >导出</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :height="tableHeight"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column label="序号" align="center" prop="id" />
      <!-- <el-table-column label="检测类别" align="center" prop="category">
        <template slot-scope="scope">
          <span>{{detection_type[category]}}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="工程名称"
        align="left"
        prop="engineeringName"
        width="250"
      />
      <!-- <el-table-column label="委托单位" align="center" prop="enterpriseName" /> -->
      <!-- <el-table-column label="委托编号" align="center" prop="gsNumber" /> -->
      <!-- <el-table-column label="委托日期" align="center" prop="commissionDate" /> -->
      <!-- <el-table-column label="检测类别" align="center" prop="businessType" /> -->
      <el-table-column label="试验项目" align="center" prop="project" >
        <template slot-scope="scope">

          <div v-for="item in scope.row.projectParamarr" :key="item.id">
            {{item.testMethod}} {{item.testNumber}}{{item.unit}}
          </div>

        </template>
      </el-table-column>
      <el-table-column label="报告编号" align="center" prop="reportNumber" />

      <el-table-column label="报告日期" align="center" prop="reportDate" />

      <!-- <el-table-column
        label="项目经理"
        align="center"
        prop="businessManagerName"
        v-if="is_yezhu == 0"
      /> -->
      <!-- <el-table-column label="试验数量" align="center" prop="testNum" />
      <el-table-column label="试验人员" align="center" prop="chargePerson"  /> -->
      <el-table-column label="检测报告" align="center" prop="reportFileName">
        <template slot-scope="scope">
          <el-link
            :href="scope.row.reportFile"
            :underline="false"
            target="_blank"
          >
            <span style="color: #1890ff">
              {{ getFileName(scope.row.reportFile) }}
            </span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="发放记录" align="center" prop="grantNum">
        <template slot-scope="scope">
          <div>{{ scope.row.grantDate }}</div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="100%"
        class-name="small-padding fixed-width"
        v-if="roleId != 6"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            >修改</el-button
          >

          <!-- <el-button size="mini" type="text" @click="handleData(scope.row)"
            >数据</el-button
          > -->

          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 新增报告 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="openSampleDialog"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" :inline="true">
        <el-row class="margin-bottom-10">
          <!-- <el-form-item label="委托单选择" prop="commissionId">
            <el-select
              v-model="form.commissionId"
              @change="handleChange"
              placeholder="请选择"
            >
              <el-option
                v-for="item in commissionListAll"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="工程选择" prop="engineeringId">
            <el-select
              v-model="form.engineeringId"
              @change="handleChange2"
              placeholder="请选择"
            >
              <el-option
                v-for="item in commissionListAll"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-row class="margin-bottom-10">
            <el-form-item label="是否为综合项目">
              <el-radio-group v-model="isComprehensive" @change="compreChange">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-row>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="试验项目" prop="commonId">
            <el-select
              :multiple="isComprehensive"
              v-model="form.commonId"
              placeholder="请选择"
              style="margin-right: 10px"
              @change="changeProject"
            >
              <el-option
                v-for="item in shiyanList"
                :key="item.id"
                :label="item.project"
                :value="item.id + '/' + item.project + '/' + item.unit + '/' + item.businessType" 
              ></el-option>
            </el-select>

            <!-- <el-select v-model="form.instrumentId" placeholder="请选择仪器">
              <el-option
                v-for="item in instrumentList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select> -->
          </el-form-item>
        </el-row>
        <!-- 新增的试验项目表格 -->
        <el-row class="margin-bottom-10">
          <el-table
            :data="selectedProjects"
            border
            style="width: 100%; margin-bottom: 20px"
          >
            <el-table-column
              prop="testMethod"
              label="试验项目"
              align="center"
            ></el-table-column>
            <el-table-column prop="testNumber" label="试验数量" align="center">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.testNumber"
                  :min="1"
                  size="mini"
                ></el-input-number>
                <span>{{ scope.row.unit }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row class="margin-bottom-10">
          <el-form-item label="报告编号" prop="reportNumber">
            <el-input
              v-if="isShowcreateReport"
              type="input"
              v-model="form.reportNumber"
              placeholder="请填写报告编号"
              :readonly="true"
            ></el-input>
            <el-button
              v-else
              type="primary"
              size="mini"
              @click="createReportNumber"
              >生成报告编号</el-button
            >
          </el-form-item>

          <!-- <el-form-item label="试验数量" prop="testNum">
            <el-input
              type="number"
              v-model="form.testNum"
              placeholder="请填写试验数量"
            ></el-input>
          </el-form-item> -->
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="报告文件" style="margin-bottom: 10px">
              <!-- <span v-html="form.reportFileName"></span> -->
              <fileUpload v-model="form.reportFile" :limit="1" />
            </el-form-item>
            <!-- <el-upload
                style="display:inline-block"
                class="upload-demo"
                :action="uploadUrl"
                :on-success="handleUploadSuccess"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :headers="headers"
                :before-remove="beforeRemove"
                multiple
                :limit="3"
                :on-exceed="handleExceed"
                :file-list="fileList"
              >
            <el-button size="small" style="margin-left:10px" type="text">上传</el-button>
            </el-upload> -->
          </el-col>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="报告日期">
            <el-input
              type="input"
              v-model="form.reportDate"
              :readonly="true"
              placeholder="报告日期"
            ></el-input>
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="报告发放">
            <el-col :span="5" style="margin-right: 10px" prop="grantNum">
              <el-input
                type="number"
                v-model="form.grantNum"
                placeholder="发放份数"
              ></el-input>
            </el-col>
            <el-col :span="5" style="margin-right: 10px">
              <el-input
                type="input"
                v-model="form.grantStaff"
                placeholder="发放人员"
              ></el-input>
            </el-col>
            <el-col :span="5" style="margin-right: 10px">
              <el-input
                type="input"
                v-model="form.grantDate"
                :readonly="true"
                placeholder="发放日期"
              ></el-input>
            </el-col>
            <el-col :span="5">
              <!-- <el-input
                type="input"
                v-model="form.grantType"
                placeholder="发放方式"
              ></el-input> -->

              <el-select
                v-model="form.grantType"
                placeholder="发放方式"
              >
                <el-option
                  v-for="item in report_grant_type_opeions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>

            </el-col>
          </el-form-item>
        </el-row>
        <el-row class="margin-bottom-10">
          <el-col :span="24">
            <el-form-item
              label="备注"
              prop="ipaddr"
              style="margin-bottom: 10px"
            >
              <el-input
                type="textarea"
                v-model="form.remark"
                :rows="4"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel((openSampleDialog = false))">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="openUpadteDialog"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" :inline="true">
        <!-- <el-row class="margin-bottom-10">
          <el-form-item label="委托编号">
            {{ form.gsNumber }}
          </el-form-item>
          <el-form-item label="委托单位">
            {{ form.enterpriseName }}
          </el-form-item>
        </el-row> -->

        <el-row class="margin-bottom-10">
          <el-form-item label="工程名称">
            {{ form.engineeringName }}
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <!-- <el-form-item label="业务类型">
            {{ detection_type[form.businessType] }}
          </el-form-item> -->

          <el-form-item label="试验项目">
            <!-- {{ form.project }} -->
            <div v-for="item in form.projectParamarr" :key="item.id">
              {{item.testMethod}} {{item.testNumber}}{{item.unit}}
            </div>
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="报告编号" prop="reportNumber">
            <el-input
              type="input"
              v-model="form.reportNumber"
              placeholder="请填写报告编号"
              :readonly="true"
            ></el-input>
          </el-form-item>

          <!-- <el-form-item label="试验数量" prop="testNum">
            <el-input
              type="number"
              v-model="form.testNum"
              placeholder="请填写试验数量"
            ></el-input>
          </el-form-item> -->
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="报告文件" style="margin-bottom: 10px">
              <!-- <span v-html="form.reportFileName"></span> -->
              <fileUpload v-model="form.reportFile" :limit="1" />
            </el-form-item>
            <!-- <el-upload
                style="display:inline-block"
                class="upload-demo"
                :action="uploadUrl"
                :on-success="handleUploadSuccess"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :headers="headers"
                :before-remove="beforeRemove"
                multiple
                :limit="3"
                :on-exceed="handleExceed"
                :file-list="fileList"
              >
            <el-button size="small" style="margin-left:10px" type="text">上传</el-button>
            </el-upload> -->
            <!-- <el-button v-if="form.reportFile" size="small" style="margin-left:10px" type="text">删除</el-button> -->
          </el-col>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="上传日期">
            <el-input
              type="input"
              v-model="form.reportDate"
              :readonly="true"
              placeholder="上传日期"
            ></el-input>
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="报告发放">
            <el-col :span="5" style="margin-right: 10px" prop="grantNum">
              <el-input
                type="number"
                v-model="form.grantNum"
                placeholder="发放份数"
              ></el-input>
            </el-col>
            <el-col :span="5" style="margin-right: 10px">
              <el-input
                type="input"
                v-model="form.grantStaff"
                placeholder="发放人员"
              ></el-input>
            </el-col>
            <el-col :span="5" style="margin-right: 10px">
              <el-input
                type="input"
                v-model="form.grantDate"
                :readonly="true"
                placeholder="发放日期"
              ></el-input>
            </el-col>
            <el-col :span="5">
              <!-- <el-input
                type="input"
                v-model="form.grantType"
                placeholder="发放方式"
              ></el-input> -->
              <el-select
                v-model="form.grantType"
                placeholder="发放方式"
              >
                <el-option
                  v-for="item in report_grant_type_opeions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                ></el-option>
              </el-select>
            </el-col>
          </el-form-item>

          <el-row class="margin-bottom-10">
            <el-col :span="24">
              <el-form-item
                label="备注"
                prop="ipaddr"
                style="margin-bottom: 10px"
              >
                <el-input
                  type="textarea"
                  v-model="form.remark"
                  :rows="4"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel2((openUpadteDialog = false))">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 数据（室内） -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="openShineiDialog"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" :inline="true">
        <el-row class="margin-bottom-10">
          <el-form-item label="委托编号" style="width: 300px">
            {{ form.gsNumber }}
          </el-form-item>
          <el-form-item label="委托单位">
            {{ form.enterpriseName }}
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="工程名称">
            {{ form.engineeringName }}
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="试验项目" style="width: 300px">
            {{ form.project }}
          </el-form-item>
          <el-form-item label="总数量">
            {{ form.sampleNumber }}
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item
            label="试验人员"
            style="width: 300px"
            v-show="roleId != 6 || roleId != 9"
          >
            {{ form.chargePerson }}
          </el-form-item>
          <el-form-item label="完成进度">
            {{ form.doingSum }}/{{ form.sampleNumber }}
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="试验录入">
            <el-card
              v-for="item in form.sampleRecordList"
              :key="item.id"
              class="box-card"
              style="width: 200px; margin-bottom: 10px"
            >
              <div slot="header" class="clearfix">
                <span>{{ detection_item_indoor[item.project] }}</span>
              </div>
              <div class="text item">检测日期：{{ item.testDate }}</div>
              <div class="text item">检测数量：{{ item.sampleNumber }}</div>
              <div class="text item">试验人员：{{ item.userName }}</div>
            </el-card>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">保存</el-button> -->
        <el-button @click="cancel3((openShineiDialog = false))">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 数据（室外） -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="openShiwaiDialog"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" :inline="true">
        <el-row class="margin-bottom-10">
          <el-form-item label="委托编号" style="width: 250px">
            {{ form.gsNumber }}
          </el-form-item>
          <el-form-item label="委托单位">
            {{ form.enterpriseName }}
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="工程名称">
            {{ form.engineeringName }}
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="试验项目" style="width: 300px">
            {{ form.project }}
          </el-form-item>
          <el-form-item label="总数量">
            {{ form.sampleNumber }}
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item
            label="试验人员"
            style="width: 300px"
            v-show="roleId != 6 || roleId != 9"
          >
            {{ form.chargePerson }}
          </el-form-item>
          <el-form-item label="完成进度">
            {{ form.doingSum }}/{{ form.sampleNumber }}
          </el-form-item>
        </el-row>

        <!-- <el-row class="margin-bottom-10">
          <el-form-item label="数据文件"  >
            {{form.chargePerson}}
          </el-form-item>
        </el-row> -->

        <el-row class="margin-bottom-10">
          <el-form-item label="报告文件">
            <a
              style="color: #1890ff"
              :href="form.reportFile"
              :download="form.reportFileName"
              >{{ form.reportFileName }}</a
            >
          </el-form-item>
        </el-row>

        <el-row class="margin-bottom-10">
          <el-form-item label="试验录入">
            <el-card
              v-for="item in form.attachedRecordList"
              :key="item.id"
              class="box-card"
              style="width: 200px; margin-bottom: 10px"
            >
              <div slot="header" class="clearfix">
                <span>{{ form.project }}</span>
              </div>
              <div class="text item">检测日期：{{ item.startTime }}</div>
              <div class="text item">检测数量：{{ item.testNumber }}</div>
              <div class="text item">
                <!-- 试验人员：{{item.userName}} -->
              </div>
            </el-card>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">保存</el-button> -->
        <el-button @click="cancel3((openShiwaiDialog = false))">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  geteditEnterprise,
  searchProject,
  getengineerProject,
} from "@/api/enterprise/enterprise";
import { getToken } from "@/utils/auth";
import { listCommissionAll } from "@/api/commission/commission";
import { listSampleAll } from "@/api/sample/sample";
import { listInstrumentAll } from "@/api/instrument/instrument";
import { listAttachedDataAll } from "@/api/attachedData/attachedData";
import {
  listReport,
  getReport,
  addReport,
  updateReport,
  delReport,
  createReportNumber,
  exportReport,
} from "@/api/report/report";
import Cookies from "js-cookie";

import orderDialog from "./components/orderFallin";
import acceptDialog from "./components/orderAccept";
export default {
  components: { orderDialog, acceptDialog },
  name: "Enterprise",
  data() {
    return {
      isComprehensive: true,
      selectedProjects: [],
      projectList: {},
      headers: { Authorization: "Bearer " + getToken() },
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      uploadDelete: false,

      detection_type_options: [],
      project_options: [],

      detection_type: [],
      instrumentList: [], //所有仪器

      detection_item_indoor_options: [],
      detection_item_indoor: [], //字典：室内检测项目
      detection_item_scene_options: [],
      detection_item_scene: [], //字典：室外检测项目

      report_grant_type_opeions:[],

      commissionListAll: [], //所有委托单
      shiyanQuery: {
        commissionId: 0,
      }, //试验项目搜索条件
      shiyanList: [], //所有试验项目
      formParams: {},
      fileList: [],
      openSampleDialog: false,
      openUpadteDialog: false,
      openShineiDialog: false,
      openShiwaiDialog: false,
      tableHeight: 0,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 企业信息表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      openDialog: false,
      openAcceptDialog: false,
      // 企业类型字典
      typeOptions: [],
      // 状态 1=开业，2=停业字典
      statusOptions: [],
      options: [
        {
          label: "11",
          value: "11",
        },
      ],
      businessType: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reportNumber: "",
        chargePerson: "",
        enterpriseName: "",
        engineeringName: "",
        startCreateTime: "",
        category: "",
        project: "",
        params: {},
      },
      // 表单参数
      form: {
        // pageNum: 1,
        reportDate: "2025-05-18",
        grantDate: "2025-05-18",
        sampleOne: {},
        sampleRecordList: [],
        attachedDataOne: {},
        attachedRecordList: [],
        businessType: "",
        engineeringId: "",
      },
      // 表单校验
      rules: {
        commissionId: [
          { required: true, message: "请选择委托单", trigger: "blur" },
        ],
        commonId: [
          { required: true, message: "请选择试验项目", trigger: "blur" },
        ],

        reportNumber: [
          { required: true, message: "报告编号不能为空", trigger: "blur" },
        ],
        testNum: [
          { required: true, message: "检测数量不能为空", trigger: "blur" },
        ],
        reportFile: [
          { required: true, message: "请上传文件", trigger: "blur" },
        ],
        grantNum: [
          { required: true, message: "发放日期不能为空", trigger: "blur" },
        ],
      },
      //创建报告编号搜索
      createReportQuery: {
        commissionId: "",
        project: "",
        businessType: "",
      },
      isShowcreateReport: false,
      roleId: null,
      roles: [],
      enterpriseId: null,
      // 日期范围
      dateRange: [],
      is_yezhu: 0,
    };
  },
  created() {
    //当前用户的信息
    let userInfo = JSON.parse(Cookies.get("userinfo"));
    this.roles = userInfo.roles;
    this.roleId = userInfo.roleId;
    this.enterpriseId = userInfo.enterpriseId;

    //业主不让看 工程编号 和 项目经理
    for (let i = 0; i < this.roles.length; i++) {
      if (this.roles[i].roleId == 6 || this.roles[i].roleId == 9) {
        this.is_yezhu = 1;
      }
    }

    // this.listCommissionAll(); //所有委托单
    this.listEngineeringAll(); //所有工程
    this.listInstrumentAll(); //所有仪器

    this.calHeight();
    this.getDicts("gc_enterprise_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("gc_enterprise_status").then((response) => {
      this.statusOptions = response.data;
    });

    //报告发放方式   
    this.getDicts("gc_report_grant_type").then((response) => {
      this.report_grant_type_opeions = response.data;
    });
    //检测类型
    this.getDicts("detection_type").then((response) => {
      let data = response.data;
      this.detection_type_options = data;
      let new_arr = [];
      data.forEach(function (item) {
        new_arr[item.dictValue] = item.dictLabel;
      });
      this.detection_type = new_arr;
    });

    //室内字典
    this.getDicts("detection_item_indoor").then((response) => {
      let data = response.data;
      let new_arr = [];
      data.forEach(function (item) {
        new_arr[item.dictValue] = item.dictLabel;
      });
      this.detection_item_indoor = new_arr;
      this.detection_item_indoor_options = data;
    });

    //室外字典
    this.getDicts("detection_item_scene").then((response) => {
      let data = response.data;
      let new_arr = [];
      data.forEach(function (item) {
        new_arr[item.dictValue] = item.dictLabel;
      });
      this.detection_item_scene = new_arr;
      this.detection_item_scene_options = data;
    });

    this.getList();
    this.riqi();
  },
  watch: {
    showSearch: "calHeight",
  },
  methods: {
    compreChange(item) {
      console.log(item,'----------');
      this.form.commonId = null
      this.selectedProjects = []
    },
    changeProject(item) {
      // 如果不是综合项目就只留单个
      if (this.isComprehensive) {
        let arr = [];
        item.map((data) => {
          let info = data.split("/");
          let obj = {
            id: info[0],
            testMethod: info[1],
            testNumber: 0,
            unit: info[2],
            businessType: info[3],
          };
          arr.push(obj);
        });
        this.selectedProjects = arr;
      } else {
        let testMethod = item.split("/");
        let obj = {
          id: testMethod[0],
          testMethod: testMethod[1],
          testNumber: 0,
          unit: testMethod[2],
          businessType: testMethod[3],
        };
        this.selectedProjects = [obj];
      }
      console.log(this.selectedProjects);
    },
    /** 列表 */
    getList() {
      let _this = this;
      this.loading = true;

      // for (let i = 0; i < this.roles.length; i++) {
      //   if (this.roles[i].roleId == 6 || this.roles[i].roleId == 9) {
      //     this.queryParams.enterpriseId = this.enterpriseId;
      //     break;
      //   }
      // }

      if (this.queryParams.params.projects) {
        this.queryParams.params["projectstr"] =
          this.queryParams.params.projects.join(",");
      }
      this.queryParams.isRoleShow = 1;
      listReport(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          let list = response.rows;
          list.forEach(function (item) {
            item.businessType = _this.detection_type[item.category];
            item.reportHref = process.env.VUE_APP_BASE_API + item.reportFile;
            if(item.projectParam){
              item.projectParamarr = JSON.parse(item.projectParam);
            }else{
              item.projectParamarr = [];
            }
          });
          console.log("_____tangyin")
          console.log(list);
          this.list = list;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    riqi() {
      // //当天日期
      let today = new Date();
      const currentDate =
        today.getFullYear() +
        "-" +
        (today.getMonth() + 1) +
        "-" +
        today.getDate();
      // console.log("riqihahaha")
      // console.log(currentDate)
      this.form.reportDate = currentDate;
      this.form.grantDate = currentDate;
    },

    //类型 室内室外 下拉
    handleDetectionTypeChange(val) {
      console.log("ddgg:" + val);
      if (val == "shinei") {
        console.log(this.detection_item_indoor_options)
        this.project_options = this.detection_item_indoor_options;
      }
      if (val == "shiwai") {
        this.project_options = this.detection_item_scene_options;
      }
      console.log(this.project_options);
    },
    // 工程 下拉选择
    handleChange2() {
      getengineerProject(this.form.engineeringId).then((res) => {
        this.form.commonId = null;
        this.selectedProjects = [];
        this.form.reportNumber = "";
        this.isShowcreateReport = false;
        console.log(res);
        if (res.code == 200) {
          let data = res.data;
          let arr = [];
          if (data.sampleList.length) {
            data.sampleList.forEach((item) => {
              let obj = {};
              obj.id = item.id;
              obj.project = item.projectName;
              obj.unit = item.unit;
              obj.businessType = item.businessType;
              console.log(obj);
              arr.push(obj);
            });
          }
          if (data.attachedDataList.length) {
            data.attachedDataList.forEach((item) => {
              let obj = {};
              obj.id = item.id;
              obj.project = item.testMethod;
              obj.unit = item.unit;
              obj.businessType = item.businessType;
              console.log(obj);
              arr.push(obj);
            });
          }
          this.shiyanList = arr;
          //this.projectList = res.data;
          // if (res.data.sampleList.length) {
          //   this.shiyanList = res.data.sampleList;
          //   this.form.businessType = "shinei";
          // } else {
          //   this.shiyanList = res.data.attachedDataList;
          //   this.form.businessType = "shiwai";
          // }
        }
      });
    },
    // 委托单 下拉选择
    handleChange() {
      let _this = this;
      this.shiyanQuery = {};
      let commission_id = this.form.commissionId;
      let commissionListAll = this.commissionListAll;
      let businessType;

      commissionListAll.forEach(function (item) {
        if (commission_id == item.id) {
          businessType = item.businessType;
        }
      });
      this.businessType = businessType;
      this.shiyanList = [];
      this.shiyanQuery.commissionId = commission_id;
      // this.shiyanQuery.originalNumber = "notempty"

      this.createReportQuery.commissionId = commission_id;
      this.createReportQuery.businessType = businessType;
      if (businessType == "shinei") {
        listSampleAll(this.shiyanQuery).then((response) => {
          let data = response.data;
          data.forEach(function (item) {
            item.label = _this.detection_item_indoor[item.project];
            item.projectNew = _this.detection_item_indoor[item.project];
            item.commonId = item.id;
          });
          this.shiyanList = data;
        });
      } else {
        console.log("室外");
        listAttachedDataAll(this.shiyanQuery).then((response) => {
          let data = response.data;
          // console.log(data)
          data.forEach(function (item) {
            item.label = item.testMethod;
            item.project = item.testMethod;
            item.projectNew = item.testMethod;
            item.commonId = item.id;
          });
          ("");
          this.shiyanList = data;
        });
      }
    },
    // 试验项目 下拉选择
    handleProjectChange(id) {
      let _this = this;
      let shiyanList = this.shiyanList;
      this.shiyanQuery.businessType = this.businessType;
      if (this.businessType == "shinei") {
        console.log(shiyanList);
        shiyanList.forEach(function (item) {
          if (item.id == id) {
            _this.form.project = item.projectNew;
            //_this.form.reportNumber = item.originalNumber
            _this.form.sampleId = item.commonId;

            _this.createReportQuery.project = item.project;
            _this.createReportQuery.sampleId = item.commonId;
          }
        });
      } else {
        shiyanList.forEach(function (item) {
          if (item.id == id) {
            _this.form.project = item.projectNew;
            //_this.form.reportNumber = item.originalNumber
            _this.form.attachedDataId = item.commonId;

            _this.createReportQuery.project = item.project;
            _this.createReportQuery.attachedDataId = item.commonId;
          }
        });
      }

      this.isShowcreateReport = false;
    },

    //生成报告编号
    createReportNumber() {
      let _this = this;
      // if (this.createReportQuery.commissionId == "") {
      //   this.msgError("请选择委托单");
      //   return false;
      // }

      // 判断this.form.commonId是否为空 它有可能是字符有可能是数组

      if (this.form.commonId == "") {
        this.msgError("请选择试验项目");
        return false;
      }
      if (!this.form.commonId.length) {
        this.msgError("请选择试验项目");
        return false;
      }
      if(this.form.commonId){
        // 判断如果是数组的话
        let str = []
        if(Array.isArray(this.form.commonId)){
          // 遍历commonId
          this.form.commonId.forEach(item => {
            let list = item.split('/')[1]
            str.push(list)
          })
        }else{
          let list = this.form.commonId.split('/')[1]
          str.push(list)
        }
        let isSubmit = 1;
        this.selectedProjects.forEach(function (item) {
          if(!item.testNumber){
            isSubmit = 2
          }
        });
        if(isSubmit == 2){
          _this.msgError("有试验项目没输入数量，请输入数量");
          return false;
        }
        this.form.projectStr = str.join(',')
        this.form.isZhonghe = this.isComprehensive ? 2 : 1;
        this.form.projectParam = JSON.stringify(this.selectedProjects);
        this.form.projectOld = this.createReportQuery.project;
        this.form.businessType = this.createReportQuery.businessType;

        createReportNumber(_this.form).then((response) => {
          console.log("dgd");
          console.log(response);
          _this.form.id = response.data.id;
          _this.form.reportNumber = response.data.reportNumber;
          _this.isShowcreateReport = true;
        });
      }
    },

    closeAcceptDialog() {
      this.openAcceptDialog = false;
    },
    calHeight() {
      this.$nextTick(() => {
        const rect = this.$refs.appcontainer.getBoundingClientRect();
        let height = this.$refs.queryForm.$el.offsetHeight;
        this.tableHeight = rect.height - height - 120;
      });
    },
    listEngineeringAll() {
      searchProject({ isRoleShow: 1 }).then((response) => {
        // let data = response.data;
        // data.forEach(function (item) {
        //   item.name = item.enterpriseName;
        // });

        this.commissionListAll = response.data;
      });
    },
    // listCommissionAll() {
    //   listCommissionAll({ status: "jcdone" }).then((response) => {
    //     let data = response.data;
    //     data.forEach(function (item) {
    //       item.name =
    //         "(编号：" + item.number + ")委托单位：" + item.enterpriseName;
    //     });

    //     this.commissionListAll = data;
    //   });
    // },

    listInstrumentAll() {
      listInstrumentAll().then((response) => {
        let data = response.data;
        data.forEach(function (item) {
          item.label =
            "(编号：" +
            item.instrumentNumber +
            ")委托单位：" +
            item.instrumentName;
        });
        this.instrumentList = data;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancel2() {
      this.openUpadteDialog = false;
      this.reset();
    },
    cancel3() {
      console.log("tangdd");
      this.openShineiDialog = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {};
      this.isShowcreateReport = false;
      this.riqi();
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.showSearch = false;
      this.queryParams.pageNum = 1;

      console.log("chaxun:");
      console.log(this.queryParams);

      this.getList();
    },
    handleAccept(row) {
      this.openAcceptDialog = true;
      this.title = "委托单受理";
    },
    handleCollar() {},
    handleReport() {},
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        reportNumber: "",
        chargePerson: "",
        enterpriseName: "",
        engineeringName: "",
        startCreateTime: "",
        category: "",
        project: "",
        params: {},
      };
      this.project_options = [];
      this.dateRange = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.openSampleDialog = true;
      this.title = "新增报告";
       // 清空试验项目表格
      this.selectedProjects = [];
      // 清空下拉选择试验项目
      this.project_options = [];

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getReport(id).then((response) => {
        let data = response.data
        data.projectParamarr = JSON.parse(data.projectParam);
        this.form = data;
        this.openUpadteDialog = true;
        this.title = "修改报告";
      });
    },
    // 数据
    handleData(row) {
      let _this = this;
      this.reset();
      const id = row.id;
      getReport(id).then((response) => {
        console.log("tangyin");
        console.log(response.data);
        let data = response.data;

        // data.sampleRecordList.forEach(function (item2) {
        //   item2.project = _this.detection_item_indoor[item2.project]
        // });
        this.form = data;
        // console.log(data)

        if (response.data.businessType == "shinei") {
          this.openShineiDialog = true;
          this.title = "试验数据（室内）";
        } else {
          this.openShiwaiDialog = true;
          this.title = "试验数据（现场）";
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateReport(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.openSampleDialog = false;
              this.openUpadteDialog = false;
              // this.resetQuery();
              this.getList();
            });
          } else {
            this.form.isZhonghe = this.isComprehensive ? 2 : 1;
            

            this.form.projectParam = this.selectedProjects;
            addReport(this.form).then((response) => {
              this.msgSuccess("新增成功");
              geteditEnterprise(this.form.commissionId).then((res) => {
                this.sendNotice(res, this.form.project);
              });
              this.openSampleDialog = false;
              this.openUpadteDialog = false;
              this.getList();
            });
          }
        }
      });
    },
    sendNotice(data, project) {},
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delReport(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有企业信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportEnterprise(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    handleUploadSuccess(res, file) {
      this.form.reportFile = res.fileName2;
      this.form.reportFileName = res.originalFilename;
    },
    handleUploadError() {
      this.$message.error("图片插入失败");
    },
    // 文件删除操作
    handleRemove(file, fileList) {
      this.reportFile = "";
      this.reportFileName = "";
    },
    handlePreview() {
      console.log("handlePreview");
    },
    handleRemove() {
      console.log("handleRemove");
    },
    beforeRemove() {
      console.log("beforeRemove");
    },
    handleExceed() {
      console.log("handleExceed");
    },

    // 获取文件名称
    getFileName(name) {
      if (name) {
        if (name.lastIndexOf("/") > -1) {
          return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
        } else {
          return "";
        }
      } else {
        return "";
      }
    },
    resetExport() {
      const ids = this.ids;
      this.queryParams.ids = ids;
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出报告管理数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportReport(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
